package com.hhyx.execl.config;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @author: Markerccc
 * @date: 2019/7/10 - 13:38
 */
@Slf4j
@Configuration
public class ThreadConfig implements AsyncConfigurer {

    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        ThreadFactory threadFactory = new ThreadFactoryBuilder()
                .setNameFormat("execl-pool-%d")
                .build();

        return new java.util.concurrent.ThreadPoolExecutor(5,
                5,
                0L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(), threadFactory);
    }

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(20);
        //最大线程数
        executor.setMaxPoolSize(40);
        //队列容量
        executor.setQueueCapacity(300);
        //活跃时间
        executor.setKeepAliveSeconds(50);
        //线程名字前缀
        executor.setThreadNamePrefix("my-execl-");

        // setRejectedExecutionHandler: 当pool已经达到max size的时候，如何处理新任务
        // DiscardPolicy: 丢弃当前将要加入队列的任务本身
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (arg0, arg1, arg2) -> {
            log.error("==========================" + arg0.getMessage() + "=======================",
                    arg0);
            log.error("exception method:" + arg1.getName());
        };
    }
}
